﻿using MyPLC.Entity;
using MyPLC.Helper;
using MyPLC.Services;
using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace MyPLC
{
    public partial class FormMain : Form
    {
        private static Dapper dapper = new Dapper();
        public FormMain()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 开始采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTrace_Click(object sender, EventArgs e)
        {
            try
            {
                lblResult.Text = "正在采集中...";
                btnTrace.Text = "正在采集...";
                btnTrace.Enabled = false;
                LoggerHelper.Info("***********Start******************");
                var listServers = listserver.Items;
                if(listServers != null && listServers.Count > 0)
                {
                    foreach(var item in listServers)
                    {
                        string server = item.ToString();
                        if(!string.IsNullOrWhiteSpace(server))
                        {
                            string[] ips = server.Split(':');
                            LoggerHelper.Info(string.Format("Server:{0}", server));
                            if(ips.Count() == 3)
                            {
                                string device = ips[0].Trim();
                                string ip = ips[1].Trim();
                                int port = 0;
                                int.TryParse(ips[2].Trim(), out port);
                                var service = new PLCService(device,ip, port);
                                if(service.ConnectSuccess())
                                {
                                    //LoggerHelper.Info("service.Write");
                                    //service.Write();

                                    listtrace.Items.Add(item);
                                    //温度
                                    Thread signalThread = new Thread(new ThreadStart(service.SyncSignalOrderInvoke));
                                    signalThread.Start();

                                    //振动压力
                                    Thread zdylThread = new Thread(new ThreadStart(service.SyncZDYLOrderInvoke));
                                    zdylThread.Start();

                                    //电磁流
                                    Thread realThread = new Thread(new ThreadStart(service.SyncRealOrderInvoke));
                                    realThread.Start();
                                }
                                else
                                {
                                    listfail.Items.Add(item);
                                    lblResult.Text += string.Format("设备：{0} {1}连接失败！", device, ip);
                                }
                            }
                        }
                    }
                    listserver.Items.Clear();
                }
                else
                {
                    lblResult.Text = "机器数不能为空！";
                }
                btnTrace.Enabled = true;
                btnTrace.Text = "开始采集";
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(ex);
            }
        }
        #region 设置
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                string ip = txtIP.Text.Trim();
                string device = txtDevice.Text.Trim();
                if (!string.IsNullOrWhiteSpace(ip) && !string.IsNullOrWhiteSpace(txtDevice.Text)
                    && !string.IsNullOrWhiteSpace(txtPort.Text) && !string.IsNullOrWhiteSpace(txtWDPL.Text)
                    && !string.IsNullOrWhiteSpace(txtZDPL.Text) && !string.IsNullOrWhiteSpace(txtDZLPL.Text))
                {
                    string item = string.Format("{0}:{1}:{2}", device, ip, txtPort.Text.Trim());
                    LoggerHelper.Info(string.Format("DeviceInfo: {0}:{1}:{2}:{3}:{4}", device, ip, txtPort.Text,txtNetworkNumber.Text,txtNetworkStationNumber.Text));

                    if (!listserver.Items.Contains(item))
                    {
                        listserver.Items.Add(item);
                        //保存设置
                        SaveSet();
                    }
                    else
                    {
                        MessageBox.Show(string.Format("{0}，IP和端口号已经存在，请修改IP或端口！", item));
                    }
                }
                else
                {
                    MessageBox.Show("设备号，IP,端口，采集频率，脉冲信号不能为空！");
                }
            }
            catch (Exception ex)
            {
                lblResult.Text = ex.Message;
                LoggerHelper.Error(ex);
            }
        }
        
        private void SaveSet()
        {
            try
            {
                string ipAddress = string.Format("{0}:{1}", txtIP.Text.Trim(), txtPort.Text.Trim());
                tbl_set model = new tbl_set();
                model.WDPL = Convert.ToInt32(txtWDPL.Text.Trim());
                model.ZDYLPL = txtZDPL.Text.Trim();
                model.DCLPL = txtDZLPL.Text.Trim();
                model.IPAddress = ipAddress;
                model.CREATEDATE = DateTime.Now;
                if (dapper.UpdateSet(model))
                {
                    MessageBox.Show("添加成功");
                }
                else
                {
                    MessageBox.Show("添加失败，请检查输入框数据格式.");
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(ex);
                MessageBox.Show("添加失败");
            }
        }
        #endregion
    }
}
